import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
import { getRoles } from '@/utils/optionsArr.ts';
export function useListComponent() {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  const options = reactive({
    //性别
    sex: [
      {
        label: '男',
        value: 1,
        type: 'primary',
      },
      {
        label: '女',
        value: 2,
        type: 'danger',
      },
    ],
    //启用状态
    state: [
      {
        label: '启用',
        value: 1,
        type: 'success',
      },
      {
        label: '禁用',
        value: 2,
        type: 'info',
      },
    ],
  });
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    copyRoleCode: '', //复制角色code
    //分类
    tabs: {
      title: '角色名称', //分类
      search: '', //搜索
      activeKey: 'roleCode', //唯一值key
      titleKey: 'roleName', //唯一值key
      active: '', //选中值
      organizationCode: '', //机构唯一值key
      list: [], //数据
      //分类操作
      operation: [
        {
          title: '编辑',
          icon: 'Edit',
          click: (row: any, index: number) => {
            proxy.$messageInputBox(`修改角色【${row.roleName}】`, (value: string) => {
              proxy.$api.SystemManage.UpdateSystemRole({
                ...row,
                roleName: value,
              })
                .then((res: any) => {
                  proxy.$message('修改成功');
                  getTabs();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '删除',
          icon: 'Delete',
          click: (row: any, index: number) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.SystemManage.DeleteSystemRole({
                roleID: row.roleID, //	对象主键ID
              })
                .then((res: any) => {
                  proxy.$message('删除成功');
                  getTabs();
                })
                .catch(() => {});
            });
          },
        },
      ],
      //分类点击列表
      click: (row: any, index: number) => {
        clickTabs(row);
      },
      //分类新建按钮
      clickAdd: () => {
        proxy.$messageInputBox(`请填写新的角色名称`, (value: string) => {
          proxy.$api.SystemManage.AddSystemRole({
            roleName: value, // 角色中文名称
            roleEnName: '', // 角色英文名称
            roleIco: '', // 角色图标
            roleGrade: 0, // 角色等级，值越大级别越低
            roleDesc: '', // 角色描述
          })
            .then((res: any) => {
              proxy.$message('新建成功');
              getTabs();
            })
            .catch(() => {});
        });
      },
    },
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'employeeCode',
      theadCode: '', //basedatatable
      //表格-表头数据
      thead: [
        {
          label: '工号',
          prop: 'loginAccount',
          align: 'center',
          width: 120,
        },
        {
          label: '状态',
          prop: 'accountState',
          align: 'center',
          width: 80,
        },
        {
          label: '姓名',
          prop: 'employeeName',
          align: 'left',
          width: null,
        },
        {
          label: '性别',
          prop: 'employeeSexName',
          align: 'center',
          width: 120,
        },
        {
          label: '手机号',
          prop: 'mobile',
          align: 'center',
          width: 120,
        },
        {
          label: '部门',
          prop: 'departmentName',
          align: 'center',
          width: 120,
        },
        {
          label: '角色',
          prop: 'roleName',
          align: 'center',
          width: 160,
        },
      ],
      //表格-搜索数据
      search: {
        likeWords: '', // 查询关键字，空值查询全部
        accountState: -1, //账户状态：0未启用；1可用（已启用）；2禁用，-1查询全部
        roleCode: '', //角色代码，空值查询全部
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.SystemManage.QueryMatchSystemUserDataList({
                  ...dataInfo.table.search,
                  roleCode: dataInfo.tabs.active, //角色编码
                })
                  .then((res: any) => {
                    exportBtn(res);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
      ],
    },
    permission: [], //角色权限
    permissionSpecial: [], //特殊权限
  });
  // 获取tabs数据
  const getTabs = () => {
    setLoading();
    proxy.$api.SystemManage.QueryMatchSystemRoleDataList({
      likeWords: '',
    }).then((res: any) => {
      dataInfo.tabs.list = res;
      if (!dataInfo.tabs.active) {
        clickTabs(res[0]);
      }
    });
  };
  // 获取tabs数据
  const clickTabs = (row: any) => {
    if (row) {
      dataInfo.tabs.active = row.roleCode;
      dataInfo.table.title = `${page.title}【${row.roleName}】`;
      dataInfo.table.checkbox.list = [];
      getTbody();
      getPermission();
      getPermissionSpecial();
    }
  };
  // 获取权限
  const getPermission = () => {
    proxy.$api.SystemManage.GetAccessDataBySystemRole({
      roleCode: dataInfo.tabs.active, //角色编码
    })
      .then((res: any) => {
        dataInfo.permission = res;
      })
      .catch(() => {});
  };
  // 获取特殊权限
  const getPermissionSpecial = () => {
    proxy.$api.SystemManage.GetSpecificPermissionByRoleCode({
      roleCode: dataInfo.tabs.active, //角色编码
    })
      .then((res: any) => {
        dataInfo.permissionSpecial = res;
      })
      .catch(() => {});
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.SystemManage.QueryMatchSystemUserDataList({
      ..._table.search,
      roleCode: dataInfo.tabs.active, //角色编码
    })
      .then((res: any) => {
        _table.tbody = res;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[]) => {
    proxy.$exportData(
      {
        thead: dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    setTimeout(() => {
      dataInfo.loading = false;
    }, 1000);
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  onMounted(() => {
    getRoles(options, 'roles'); //获取所有客户
  });
  // 组件挂载后执行
  onMounted(() => {
    getTabs();
  });
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, options };
}
